/*
 * Copyright 2015 Pivotal Software, Inc..
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.joomtu.smarterlife.controllers.admin;

import com.joomtu.smarterlife.entities.User;
import com.joomtu.smarterlife.forms.UserRegisterForm;
import com.joomtu.smarterlife.services.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author huguobing
 */
@Controller
@RequestMapping("/admin/user")
public class AdminUserController {

    @Autowired
    private UserService userServiceImple;

    @RequestMapping("/login")
    public String login(Model model, HttpServletRequest request) {
        if ("get".equals(request.getMethod().toLowerCase())) {
            Object principal = SecurityContextHolder.getContext()
                    .getAuthentication().getPrincipal();
            if (principal instanceof User) {
                return "redirect:/";
            }
            return "user/login";
        } else {
            return "redirect:/";
        }
    }

    @RequestMapping("/logout")
    public String logout() {
        return "redirect:/";
    }

    @RequestMapping("/register")
    public String register(@Valid UserRegisterForm userRegisterForm, BindingResult bindingResult, Model model, HttpServletRequest request) {
        if ("get".equals(request.getMethod().toLowerCase())) {
            return "user/register";
        }
        if (bindingResult.hasErrors()) {
            return "user/register";
        }
        if (userServiceImple.register(userRegisterForm)) {
            return "user/registerOk";
        }
        model.addAttribute("errorCode", userServiceImple.getCode());
        model.addAttribute("errorMessage", userServiceImple.getMessage());
        return "user/register";

    }

    @RequestMapping("/forget")
    public String forgetPassword() {
        return "user/forgetPassword";
    }

}
